package com.ganwei.mybatisplus.config.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.http.MediaType;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Djh
 */
@Slf4j
public class ExcelUtil {

    /**
     * 利用正则的预编译功能
     */
    private static Pattern NUMBER_PATTERN = Pattern.compile("^//d+(//.//d+)?$");

    /**
     * 导出Excel工具
     *
     * @param fileName  文件名
     * @param sheetName sheet名称
     * @param headers   第一列内容，表头
     * @param dataSet   内容
     * @param keyList   map键，用于排序
     * @param response  response
     * @param pattern   日期格式化
     * @throws IOException IO异常
     */
    public static void exportExcel(String fileName, String sheetName, String[] headers,
                                   List<Map<String, Object>> dataSet, String[] keyList, HttpServletResponse response, String pattern) throws IOException {
        exportExcel(fileName, sheetName, headers, dataSet, keyList, new AbstractExcelInfo<Map<String, Object>>() {
            @Override
            public Map<String, Object> getRowDataMap(Map<String, Object> rowData) {
                return rowData;
            }
        }, response, pattern);
    }


    private static <T> void exportExcel(String fileName, String sheetName, String[] headers,
                                        List<T> dataSet, String[] keyList, AbstractExcelInfo<T> iExcelInfo, HttpServletResponse response, String pattern) throws IOException {
        // 声明一个工作薄
        SXSSFWorkbook workbook = new SXSSFWorkbook(100);
        CellStyle cellStyle = getCellStyle(workbook);

        // 生成一个表格
        SXSSFSheet sheet = workbook.createSheet(sheetName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 15);
        setTitle(sheet, headers);

        Font font3 = workbook.createFont();
        font3.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());

        // 声明一个画图的顶级管理器
        SXSSFDrawing patriarch = sheet.createDrawingPatriarch();

        // 遍历集合数据，产生数据行
        Iterator<T> it = dataSet.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            T next = it.next();
            Map<String, Object> rowDataMap = null;
            List<Object> rowData = null;
            int dataSize;
            if (keyList != null) {
                rowDataMap = iExcelInfo.getRowDataMap(next);
                dataSize = keyList.length;
            } else {
                rowData = iExcelInfo.getRowData(next);
                dataSize = rowData.size();
            }

            SXSSFRow row = sheet.createRow(index);
            //根据key的顺序依次从数据中拿到需要的数据，并生成所需要的单元格
            for (int i = 0; i < dataSize; i++) {
                SXSSFCell cell = row.createCell(i);
                cell.setCellStyle(cellStyle);
                Object value;
                if (keyList != null) {
                    String key = keyList[i];
                    value = rowDataMap.get(key);
                } else {
                    value = rowData.get(i);
                }


                String textValue;
                if (value instanceof byte[]) {
                    setPic(row, sheet, patriarch, (byte[]) value, i, index);
                } else {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
                    textValue = getTextObject(value, formatter);
                    if (textValue != null) {
                        Matcher matcher = NUMBER_PATTERN.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            HSSFRichTextString richString = new HSSFRichTextString(
                                    textValue);

                            richString.applyFont(font3);
                            cell.setCellValue(richString);
                        }
                    }
                }
            }
        }
        setResponseHeader(response, fileName);
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
    }
    /**
     * 导出Excel工具
     *
     * @param fileName  文件名
     * @param sheetName sheet名称
     * @param response  response
     * @param pattern   日期格式化
     * @throws IOException IO异常
     */
    public static <T> void exportObjectExcel(String fileName, String sheetName, String[] headers, List<T> dataList, AbstractExcelInfo<T> iExcelInfo, HttpServletResponse response, String pattern) throws IOException {

        exportExcel(fileName, sheetName, headers, dataList, null, iExcelInfo, response, pattern);
    }

    /**
     * 导出Excel工具,
     *
     * @param fileName  文件名
     * @param sheetName sheet名称
     * @param response  response
     * @param pattern   日期格式化
     * @throws IOException io异常
     */
    public static <T> void exportObjectExcel(String fileName, String sheetName, String[] headers, List<T> dataList, String[] keyList, HttpServletResponse response, String pattern) throws IOException {

        exportExcel(fileName, sheetName, headers, dataList, keyList, new AbstractExcelInfo<T>() {
            @Override
            public Map<String, Object> getRowDataMap(T rowData) {
                return (JSONObject)JSONObject.toJSON(rowData);
            }
        }, response, pattern);
    }

    private static void setXSSFResponseHeader(HttpServletResponse response, String fileName) {
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        String headerValue = "attachment;";
        headerValue += " filename=\"" + encodeURIComponent(fileName + ".xlsx") +"\";";
        headerValue += " filename*=utf-8''" + encodeURIComponent(fileName + ".xlsx");
        response.setHeader("Content-Disposition", headerValue);
    }

    private static void setResponseHeader(HttpServletResponse response, String fileName) {
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        String headerValue = "attachment;";
        headerValue += " filename=\"" + encodeURIComponent(fileName + ".xls") +"\";";
        headerValue += " filename*=utf-8''" + encodeURIComponent(fileName + ".xls");
        response.setHeader("Content-Disposition", headerValue);
    }

    public static String getTextObject(Object value, DateTimeFormatter sdf) {
        if (value == null) {
            return "";
        } else if (value instanceof Date) {
            ZoneId zone = ZoneId.systemDefault();
            Date date = (Date) value;
            return sdf.format(date.toInstant().atZone(zone).toLocalDateTime());
        } else if (value instanceof LocalDateTime) {
            return ((LocalDateTime) value).format(sdf);
        } else {
            return value.toString();
        }
    }

    /**
     * 设置表格头
     * @param sheet sheet
     * @param headers 标题数组
     */
    private static void setTitle(Sheet sheet, String[] headers) {
        Workbook workbook = sheet.getWorkbook();
        CellStyle style = getHeaderStyle(workbook);
        // 生成一个字体
        Font font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 产生表格标题行
        Row row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
    }

    private static void setPic(Row hssfRow, Sheet sheet, SXSSFDrawing patriarch, byte[] value, int col, int row) {
        // 有图片时，设置行高为60px;
        hssfRow.setHeightInPoints(60);
        // 设置图片所在列宽度为80px,注意这里单位的一个换算
        sheet.setColumnWidth(col, (short) (35.7 * 80));
        // sheet.autoSizeColumn(i);
        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
                1023, 255, (short) 6, row, (short) 6, row);
        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
        patriarch.createPicture(anchor, sheet.getWorkbook().addPicture(
                value, HSSFWorkbook.PICTURE_TYPE_JPEG));
    }

    /**
     * 标题的样式
     * @return
     */
    public static CellStyle getHeaderStyle(Workbook workbook) {
        DefaultIndexedColorMap colorMap = new DefaultIndexedColorMap();
        XSSFColor titleBgColor = new XSSFColor(new Color(0xDD, 0xEB, 0xF7), colorMap);
        CellStyle cellStyle = workbook.createCellStyle();
        ExcelUtil.setCellStyle(cellStyle);
        ((XSSFCellStyle)cellStyle).setFillForegroundColor(titleBgColor);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font font = workbook.createFont();
        font.setFontHeight((short) (12 * 20));
        font.setFontName("宋体");
        font.setBold(true);
        cellStyle.setFont(font);

        return cellStyle;
    }

    public static void setCellStyle(CellStyle cellStyle) {
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
    }

    public static CellStyle getCellStyle(SXSSFWorkbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        setCellStyle(cellStyle);
        cellStyle.setVerticalAlignment(VerticalAlignment.TOP);
        cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        cellStyle.setWrapText(true);
        return cellStyle;
    }

    public static void output(Workbook workbook, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (workbook instanceof HSSFWorkbook) {
            setResponseHeader(response, fileName);
        } else {
            setXSSFResponseHeader(response, fileName);
        }

        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
    }

    public static String encodeURIComponent(String value) {
        try {
            return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
